<?php

namespace App\Exports;

use App\Models\Agent;
use App\Models\IndicatorsDailySummary;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Concerns\FromQuery;

class PartnerExport extends BaseExport implements FromQuery
{
    public function headings(): array
    {
        return [
            '序号',
            '合伙人名称',
            '合伙人手机号',
            '合伙人等级',
            '合伙人业绩',
            '合伙人奖励',
            '晋升时间',
        ];
    }

    public function map($row): array
    {
        $row = $row->toArray();

        return [
            $row['id'], // 序号
            $row['name'], // 合伙人名称
            $row['phone'], // 合伙人手机号
            Agent::LEVEL_MAP[$row['partner_identity']['level']]['text'], // 合伙人等级
            number_format((array_key_exists( 'performance', $row) ? ($row['performance'] ?? 0) : $row['partner_identity']['performance']) / 100, 2), // 合伙人业绩
            number_format((array_key_exists( 'reward', $row) ? ($row['reward'] ?? 0) : $row['partner_identity']['reward']) / 100, 2), // 合伙人业绩
            $row['partner_identity']['created_at'], // 晋升时间
        ];
    }

    /**
     * @return \Illuminate\Database\Query\Builder
     */
    public function query()
    {
        return Agent::query()
            ->with('partnerIdentity')
            ->whereHas('partnerIdentity', function (Builder $builder) {
                $builder
                    ->when($this->request['level'] ?? 0, function (Builder $builder, $level) {
                        $builder->where('level', $level);
                    })
                    ->when($this->request['created_at_begin'] ?? '', function (Builder $builder, $createdAtBegin) {
                        $builder->where('created_at', '>=', $createdAtBegin);
                    })
                    ->when($this->request['created_at_end'] ?? '', function (Builder $builder, $createdAtEnd) {
                        $builder->where('created_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
                    });
            })
            ->when($this->request['name'] ?? '', function (Builder $builder, $name) {
                $builder->where('name', 'like', "%$name%");
            })
            ->when($this->request['phone'] ?? '', function (Builder $builder, $phone) {
                $builder->where('phone', 'like', "%$phone%");
            })
            ->when(
                ($this->request['performance_range_begin'] ?? '') && ($this->request['performance_range_end'] ?? ''),
                function (Builder $builder) {
                    $builder
                        ->select([
                            'agents.id', 'agents.name', 'agents.phone',
                        ])
                        ->selectSub(
                            // 业绩按日期范围汇总
                            \DB::table('indicators_daily_summary')
                                ->selectRaw('sum(performance_summary)')
                                ->whereBetween('day', [$this->request['performance_range_begin'], $this->request['performance_range_end']])
                                ->where('type', IndicatorsDailySummary::TYPE_PARTNER)
                                ->whereRaw('agent_id = agents.id'),
                            'performance'
                        )
                        ->selectSub(
                            // 佣金按日期范围汇总
                            \DB::table('indicators_daily_summary')
                                ->selectRaw('sum(commission_summary)')
                                ->whereBetween('day', [$this->request['performance_range_begin'], $this->request['performance_range_end']])
                                ->where('type', IndicatorsDailySummary::TYPE_PARTNER)
                                ->whereRaw('agent_id = agents.id'),
                            'commission'
                        )
                        ->selectSub(
                            // 奖励按日期范围汇总
                            \DB::table('indicators_daily_summary')
                                ->selectRaw('sum(reward_summary)')
                                ->whereBetween('day', [$this->request['performance_range_begin'], $this->request['performance_range_end']])
                                ->where('type', IndicatorsDailySummary::TYPE_PARTNER)
                                ->whereRaw('agent_id = agents.id'),
                            'reward'
                        );
                },
                function (Builder $builder) {
                    $builder->select(['agents.id', 'agents.name', 'agents.phone']);
                });
    }
}
